package com.idea.relax.log.support.utils;

import org.springframework.util.Assert;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @className: PlaceholderUtil
 * @description: 占位符解析工具类
 * @author: salad
 * @date: 2023/1/2
 **/
public class PlaceholderUtil {

    /**
     * 利用好其预编译功能，可以有效加快正则匹配速度
     */
    public static final Pattern PATTERN = Pattern.compile(".*\\$\\{([a-z]+)\\}.*");

    /**
     * 默认前缀占位符
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

    /**
     * 默认后缀占位符
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";


    /**
     * 占位符前缀
     */
    private String placeholderPrefix = DEFAULT_PLACEHOLDER_PREFIX;

    /**
     * 占位符后缀
     */
    private String placeholderSuffix = DEFAULT_PLACEHOLDER_SUFFIX;

    private static final PlaceholderUtil DEFAULT_RESOLVER = new PlaceholderUtil(DEFAULT_PLACEHOLDER_PREFIX,DEFAULT_PLACEHOLDER_SUFFIX);

    private PropertyPlaceholderHelper placeholderHelper;

    private PlaceholderUtil() {

    }

    private PlaceholderUtil(String placeholderPrefix, String placeholderSuffix) {
        this.placeholderPrefix = placeholderPrefix;
        this.placeholderSuffix = placeholderSuffix;
        placeholderHelper = new PropertyPlaceholderHelper(placeholderPrefix,placeholderSuffix);
    }

    public static PlaceholderUtil getDefaultResolver() {
        return DEFAULT_RESOLVER;
    }

    public static PlaceholderUtil getResolver(String placeholderPrefix, String placeholderSuffix) {
        return new PlaceholderUtil(placeholderPrefix, placeholderSuffix);
    }

    public String resolve(String value, PropertyPlaceholderHelper.PlaceholderResolver placeholderResolver){
        return placeholderHelper.replacePlaceholders(value,placeholderResolver);
    }

    public String resolve(String value, Map<String,String> valueMap){
        return placeholderHelper.replacePlaceholders(value,placeholderName -> {
            Assert.notNull(placeholderName,"'placeholderName' cannot be null!");
            Assert.notNull(valueMap,"'valueMap' cannot be null!");
            return valueMap.get(placeholderName);
        });
    }

    /**
     * 替换模板中占位符内容，占位符的内容即为map key对应的值，key为占位符中的内容
     *
     * @param content  模板内容
     * @param valueMap 值映射
     * @return 替换完成后的字符串
     */
    public String resolveByMap(String content, final Map<String, Object> valueMap) {
        return resolve(content, placeholderValue -> String.valueOf(valueMap.get(placeholderValue)));
    }

    public boolean matchPlaceholder(String value){
        Assert.notNull(value,"'value' cannot be null!");
       if (value.contains(this.placeholderPrefix) && value.contains(this.placeholderSuffix)){
           return PATTERN.matcher(value).matches();
       }
       return false;
    }

}
